<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{
          item.meta.title }}</span>
        <!--  @click.prevent="handleLink(item)" -->
        <a @click.prevent="handleLink(item, index)" v-else :class="index !== 0 ? 'breadcrumbclick' : ''">{{
          item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import pathToRegexp from 'path-to-regexp'

export default {
  data() {
    return {
      levelList: null
    }
  },
  watch: {
    $route() {
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      // only show routes with meta.title
      if (!this.$route.name) return
      // console.log(this.$route, 'aaaaxxxx')
      let route = this.$route
      let ls = route.meta.position.split('-')
      let menu = this.$store.state.permission.addRoutes
      let levelList = []

      for (let i = 0; i < ls.length; i++) {
        if (i === 0) {
          menu = menu[ls[i]]
          levelList.push(menu)
        } else {
          menu = menu.children[ls[i]]
          // 如果出现一样的title 则过滤
          if (levelList[levelList.length - 1].title == menu.title) {
            levelList[levelList.length - 1] = menu
          } else {
            levelList.push(menu)
          }
        }
      }
      if (route.query.route_title) {
        levelList[levelList.length - 1].meta.title = route.query.route_title
      }
      this.levelList = levelList
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
    },
    pathCompile(path) {
      // To solve this problem https://github.com/PanJiaChen/vue-element-admin/issues/561
      const { params } = this.$route
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item, index) {
      if (index === 0) return
      const { redirect, path } = item
      if (redirect) {
        this.$store.commit('isEventTriggeredFunc', true);
        this.$router.push(redirect)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}

.breadcrumbclick {
  cursor: pointer !important;

  &:hover {
    color: #1b2431 !important;
  }
}
</style>
